package com.eric.ipc.aidl;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.eric.ipc.R;

public class AIDLActivity extends Activity implements OnClickListener{
   private Button mPlayBtn;
   private Button mStopBtn;
   private Button mExitBtn;
   private TextView mShowText;
   private IMediaPlayer mIBinder;
   private ServiceConnection mServiceConnection = new ServiceConnection() {
	   @Override
	   public void onServiceDisconnected(ComponentName name) {
		   Log.i("XXX", "onServiceDisconnected");
	   }
	   
	   @Override
	   public void onServiceConnected(ComponentName name, IBinder service) {
		   mIBinder = IMediaPlayer.Stub.asInterface(service);
		   Log.i("XXX", "onServiceConnected");
	   }
   };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.binder_layout);
        
        mPlayBtn = (Button)findViewById(R.id.play);
        mStopBtn = (Button)findViewById(R.id.stop);
        mExitBtn = (Button)findViewById(R.id.exit);
        mShowText = (TextView)findViewById(R.id.show);
        
        mPlayBtn.setOnClickListener(this);
        mStopBtn.setOnClickListener(this);
        mExitBtn.setOnClickListener(this);
        
        Intent intent = new Intent("com.eric.ipc.aidl");
        startService(intent);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        
        mShowText.setText("aidl achieve");
    }
	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.play:
				String a = "123";
				String b = a;
				double result = 20.0;
				try {
					//result = mIBinder.add(1.0, 2.0);
					mIBinder.play();
					
					b = "456";
					System.out.println("a = " + a);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				mShowText.setText(a);
				break;
			case R.id.stop:
				try {
					mIBinder.stop();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				mShowText.setText("stop");
				break;
			case R.id.exit:
				unbindService(mServiceConnection);
				stopService(new Intent("com.eric.ipc.aidl"));
				finish();
				break;
			default :
				break;
		}
	}
}